<?php

namespace app\common\model\marketing\label;

use addons\xyb\XypHelper;
use think\Model;

class Label extends Model
{
    // 数据库
    protected $name = 'label_lists';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'status_text',
        'open_text',
        'create_date',
        'category_name'
    ];

    public function getCategoryNameAttr($value, $data)
    {
        if(!isset($data['category_id'])) return '';
        if(!$category_id = XypHelper::stringToArray($data['category_id'])){
            return '';
        }
        if(!$category =  Category::whereIn('id', $category_id)->column('name')){
            return '';
        }
        return implode('/', $category);

    }

    public function getStatusTextAttr($value, $data)
    {
        if(!isset($data['status'])) return '禁用';
        return $data['status'] == 'normal' ? '启用' : '禁用';
    }

    public function getOpenTextAttr($value, $data)
    {
        if(!isset($data['is_open'])) return '';
        return $data['is_open'] == 1 ? '显示' : '隐藏';
    }
    public function getCreateDateAttr($value, $data)
    {
        if (isset($data['createtime']) && $data['createtime']) {
            return date('Y-m-d H:i', $data['createtime']);
        } else {
            return '';
        }
    }
    public function getList($where = [], $page = 1, $limit = 10)
    {
        $total = $this->where($where)->count();
        $list = $this->where($where)
            ->page($page, $limit)
            ->order('weigh desc, id desc')
            ->select();

        return ['total' => $total, 'data' => $list];
    }
    public function add($data)
    {
        // 处理参数JSON
        if (isset($data['params']) && is_array($data['params'])) {
            $data['params'] = json_encode($data['params'], JSON_UNESCAPED_UNICODE);
        }

        return $this->allowField(true)->save($data);
    }
    public function edit($data)
    {
        // 处理参数JSON
        if (isset($data['params']) && is_array($data['params'])) {
            $data['params'] = json_encode($data['params'], JSON_UNESCAPED_UNICODE);
        }

        return $this->allowField(true)->save($data, ['id' => $data['id']]);
    }
    public function remove($id)
    {
        return $this->where('id', $id)->delete();
    }
    public function updateStatus($id, $status)
    {
        return $this->where('id', $id)->update(['status' => $status]);
    }

    public static function getListByCategoryId($parent_id)
    {
        $list = self::field('id as value,name as label')->where('parent_id', $parent_id)->where('status', 'normal')->select();
        return $list;
    }

}
